
<template>
  <div class="common-layout">
    <div class="editor-header">
      <button class="back-btn" @click="backRouter">返回</button>
      <button class="save-btn" @click="handleSave">保存</button>
    </div>
    <div class="editor-body">
      <el-container>
        <el-aside width="200px">
          <el-scrollbar height="89vh">
            <div v-if="showNavigation" class="title-navigation">
              <div class="nav-header">目录导航</div>
              <div class="nav-content">
                <div
                    v-for="(item, index) in headings"
                    :key="index"
                    :class="['nav-item', `level-${item.level}`]"
                    :style="{ paddingLeft: (item.level - 1) * 12 + 'px' }"
                    @click="scrollToHeading(item.id)"
                >
                  {{ item.text }}
                </div>
              </div>
            </div>
          </el-scrollbar>


        </el-aside>
        <el-main>

          <div class="wang-editor-container">
            <div class="editor-wrapper">
              <Toolbar
                  :defaultConfig="toolbarConfig"
                  :editor="editorRef"
                  :mode="mode"
                  class="editor-toolbar"
              />
              <Editor
                  v-model="richTextContent"
                  :defaultConfig="editorConfig"
                  :mode="mode"
                  class="editor-content"
                  @onChange="handleChange"
                  @onCreated="handleCreated"
              />
            </div>
          </div>


        </el-main>
      </el-container>
    </div>

  </div>
</template>


<script lang="ts" setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {onBeforeUnmount, ref, shallowRef, onMounted, defineProps, defineExpose, watch} from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import {IEditorConfig, IDomEditor} from '@wangeditor/editor'
import {getUserInfo} from "@/utils/system";
import {uploadTextAsFile} from "@/views/documentManager/components/ts/uploadFile";
import {isAppCollapsed} from "@/main";
import router from "@/router";
import {useRoute} from "vue-router";
import {message} from "@/utils/ElmessasgeUtils";
import {getPureTextContent} from "@/api/documentManage/minioManager2";


const route = useRoute()
const fileFullPath = route.query.fileFullPath as string;
const fileName = route.query.fileName as string;
const filePath = route.query.filePath as string;
const bucket = route.query.bucket as string;

const mode = ref('default');
const editorRef = shallowRef<IDomEditor>()
const showNavigation = ref(true) // 控制是否显示导航栏
const headings = ref<Array<{ id: string, text: string, level: number }>>([]) // 存储标题信息
const richTextContent = ref('')

onMounted(async () => {
  let response = await getPureTextContent(bucket, fileFullPath);

  if (response.data.code === 200) {
    richTextContent.value = response.data.data;
  } else {
    message("获取文件内容失败", 'error')
  }
})

const props = defineProps({
  showNav: {
    type: Boolean,
    default: true
  }
})

showNavigation.value = props.showNav

// 保存为文本文件
function handleSave() {
  uploadTextAsFile(richTextContent.value,
      filePath,
      fileName)
}

function backRouter() {
  router.back();
}

// 提取编辑器中的标题
const extractHeadings = () => {
  if (!editorRef.value) return

  const editor = editorRef.value
  const dom = editor.getEditableContainer()
  if (!dom) return

  const headingElements = dom.querySelectorAll('h1, h2, h3, h4, h5, h6')
  const newHeadings: Array<{ id: string, text: string, level: number }> = []

  headingElements.forEach((el: HTMLElement) => {
    // 确保标题有ID，如果没有则生成一个
    if (!el.id) {
      el.id = 'heading-' + Math.random().toString(36).substr(2, 9)
    }

    const level = parseInt(el.tagName.substring(1))
    newHeadings.push({
      id: el.id,
      text: el.innerText,
      level: level
    })
  })

  headings.value = newHeadings
}

// 滚动到指定标题位置
const scrollToHeading = (id: string) => {
  const editor = editorRef.value
  if (!editor) return

  const dom = editor.getEditableContainer()
  if (!dom) return

  const headingElement = dom.querySelector(`#${id}`)
  if (headingElement) {
    headingElement.scrollIntoView({behavior: 'smooth', block: 'start'})
  }
}

// 编辑器内容变化回调
const handleChange = (editor: IDomEditor) => {
  extractHeadings()
}

// 初始化编辑器配置
const editorConfig = ref<Partial<IEditorConfig>>({
  placeholder: '请输入内容...',
  scroll: true,
  MENU_CONF: {
    uploadImage: {
      server: '/documentManager/wangEditor?path=' + filePath + fileName.substring(0, fileName.lastIndexOf(".")) + '/',
      fieldName: 'custom-field-name',
      meta: {
        Authorization: getUserInfo().token,
        otherKey: 'yyy',
      },
      onProgress(progress: number) {
        console.log('progress', progress)
      },
      onSuccess(file: File, res: any) {
        console.log(`${file.name} 上传成功`, res)
      },
      onFailed(file: File, res: any) {
        console.log(`${file.name} 上传失败`, res)
      },
      onError(file: File, err: any, res: any) {
        console.log(`${file.name} 上传出错`, err, res)
      },
    },
    codeSelectLang: {
      codeLangs: [
        {text: 'HTML', value: 'html'},
        {text: 'CSS', value: 'css'},
        {text: 'JavaScript', value: 'javascript'},
        {text: 'TypeScript', value: 'typescript'},
        {text: 'Vue', value: 'vue'},
        {text: 'JSON', value: 'json'},
      ]
    }
  }
})

const toolbarConfig = {
  toolbarKeys: [
    "headerSelect",  // 标题选择
    'bold', // 加粗
    'italic', // 斜体
    'through', // 删除线
    'underline', // 下划线
    'justifyCenter', // 居中对齐
    'justifyJustify', // 两端对齐
    'justifyLeft', // 左对齐
    'justifyRight', // 右对齐
    'bulletedList', // 无序列表
    'numberedList', // 有序列表
    'color', // 文字颜色
    'insertLink', // 插入链接
    'fontSize', // 字体大小
    'lineHeight', // 行高
    'delIndent', // 缩进
    'indent', // 增进
    'divider', // 分割线
    'insertTable', // 插入表格
    'undo', // 撤销
    'redo', // 重做
    'clearStyle', // 清除格式
    // 'fullScreen', // 全屏
    "blockquote", // 引用
    "codeBlock", // 代码块
    // "insertImage", // 插入图片
    "uploadImage", // 上传图片
    // "insertVideo", // 插入视频
  ]
}
// const toolbarConfig = {
// }

onMounted(() => {
  isAppCollapsed.value = true;

  const editor = editorRef.value
  if (editor == null) return
  setTimeout(() => {
    editor?.fullscreen()
  }, 2000)
})

onBeforeUnmount(() => {
  isAppCollapsed.value = false;
  const editor = editorRef.value
  if (editor == null) return
  editor?.destroy()
})

const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor
  // 初始提取标题
  setTimeout(() => {
    extractHeadings()
  }, 500)
}

// 暴露函数给父组件
defineExpose({
  handleSave,
  getHeadings: () => headings.value,
  toggleNavigation: () => {
    showNavigation.value = !showNavigation.value
  }
})
</script>

<style scoped>

.editor-header {
  background-color: #f5f5f5;
  padding: 8px 16px;
  border-bottom: 1px solid #ddd;
}

.back-btn {
  margin-right: 20px;
  background-color: #3e91f3;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.back-btn:hover {
  background-color: #3e91f3;
}

.save-btn {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.save-btn:hover {
  background-color: #45a049;
}

.wang-editor-container {
  border: 1px solid #ccc;
  height: 89vh; /* 直接设置高度 */
}

/* 左侧标题导航栏样式 */
.title-navigation {
  width: 220px;
  border-right: 1px solid #e8e8e8;
  background-color: #fafafa;
  overflow-y: auto;
  height: 100%;
  flex-shrink: 0;
}

.nav-header {
  padding: 12px 16px;
  font-weight: bold;
  border-bottom: 1px solid #e8e8e8;
  background-color: #f0f0f0;
}

.nav-content {
  padding: 8px 0;
}

.nav-item {
  padding: 6px 16px;
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.nav-item:hover {
  background-color: #e6f7ff;
  color: #1890ff;
}

/* 不同级别标题的样式 */
.nav-item.level-1 {
  font-weight: bold;
  font-size: 15px;
}

.nav-item.level-2 {
  font-weight: 500;
  font-size: 14px;
}

.nav-item.level-3 {
  font-size: 13px;
}

.nav-item.level-4 {
  font-size: 12px;
  color: #666;
}

.nav-item.level-5,
.nav-item.level-6 {
  font-size: 12px;
  color: #999;
}

.editor-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
}


.editor-toolbar {
  border-bottom: 1px solid #ccc;
  position: sticky;
  top: 0;
  z-index: 10;
  background: white;
}

.editor-content {
  flex: 1;
  overflow-y: auto;
  padding: 5px;
}

/* 确保编辑器容器有正确的高度 */
:deep(.w-e-text-container) {
  height: calc(100% - 41px) !important;
  overflow-y: auto !important;
}

/* 响应式设计 - 在小屏幕上隐藏导航栏 */
@media screen and (max-width: 768px) {
  .title-navigation {
    display: none;
  }

  .editor-wrapper {
    width: 100%;
  }
}
</style>